package com.coincalf.web;

import com.alibaba.fastjson.JSONObject;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.framework.geetest.GeetestLib;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.security.TokenProvider;
import com.coincalf.framework.security.UserDetails;
import com.coincalf.framework.utils.IpUtil;
import com.coincalf.service.UserDetailsService;
import com.coincalf.service.UserService;
import com.coincalf.web.vo.UserLoginForm;
import com.google.common.base.Strings;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;

/**
 * 用户登录
 *
 * @author qiang
 */
@Deprecated
@RestController
@RequestMapping
@Slf4j
@Api(value = "用户登录-PHP专用", description = "用户登录")
public class LoginController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private GeetestLib geetestLib;
    @Autowired
    private TokenProvider tokenProvider;

    @Value("${jwt.expire}")
    private long tokenExpireMillis;

    /**
     * 用户登录 该接口废弃 调用PHP那边登录 JAVA这边暂时废弃...
     *
     * @param form 登录表单
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
//    @PostMapping("/login")
//    @ApiResponses(value = {
//            @ApiResponse(code = 0, message = "请求成功", response = Response.class),
//            @ApiResponse(code = -1, message = "注册失败，系统繁忙", response = Response.class),
//            @ApiResponse(code = 40002, message = "用户已存在（手机号码已注册）", response = Response.class)
//    })
//    @ApiOperation(value = "用户登录", httpMethod = "POST")
//    public Object login(@ApiParam(value = "用户登录信息", required = true) @RequestBody @Valid UserLoginForm form, BindingResult result) throws AuthenticationException {
//        String ip = IpUtil.getIpAddr(request);
//        //自定义参数,可选择添加
//        HashMap<String, String> param = new HashMap<>();
//        param.put("user_id", "qiang"); //网站用户id
//        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
//        param.put("ip_address", ip); //传输用户请求验证时所携带的IP
//        int gtResult = geetestLib.enhencedValidateRequest(form.getGeetest_challenge(), form.getGeetest_validate(), form.getGeetest_seccode(), param);
//        if (true) {
//            //if (gtResult == 1) {
//            // 验证成功
//            UserDetails userDetails = userDetailsService.login(form);
//            return Response.ok(userDetails);
//        } else {
//            // 验证失败
//            throw new GlobalDefaultException(40011);
//        }
//    }

    /**
     * 刷新密钥
     *
     * @param authorization 原密钥
     * @return 新密钥
     * @throws AuthenticationException 错误信息
     */
    //@GetMapping(value = "/refreshToken")
    //@ApiOperation(value = "刷新密钥", httpMethod = "GET", authorizations = {@Authorization(value = "Authorization")})
    //@PreAuthorize("isAuthenticated()")
    //public Object refreshToken(@ApiIgnore @RequestHeader String authorization) throws AuthenticationException {
    //    String accessToken = tokenProvider.resolveToken(request);
    //    if (!Strings.isNullOrEmpty(accessToken)) {
    //        String jwt = userDetailsService.refreshToken(accessToken);
    //        JSONObject result = new JSONObject();
    //        result.put("access_token", jwt);
    //        result.put("expire", tokenExpireMillis);
    //        return Response.ok(result);
    //    } else {
    //        //无效凭证，access_token无效或不是最新的。
    //        throw new GlobalDefaultException(40001);
    //    }
    //}

    /**
     * 获取access_token（机器人专用）
     *
     * @return
     */
    //@GetMapping("/cgi-bin/token")
    //@ApiOperation(value = "获取access_token（机器人专用）")
    //public Object oauthToken(String access_key, String secret) {
    //    UserDetails userDetails = userDetailsService.oauth(access_key, secret);
    //    return Response.ok(userDetails);
    //}

    // 登录服务  前端调用PHP那边登录 PHP再调用我这边该接口 token token包含关键信息 用户名 密码 国家区号
    //@PostMapping("/login")
    //public String login(String token) {
    //    if (StringUtils.isEmpty(token)) {
    //        return "TOKEN不能为空";
    //    }
    //    try {
    //        //用户登录 调用该接口 生成UserDetail信息 便于后续调用其他接口
    //        return userDetailsService.phpLogin(token);
    //    } catch (Exception e) {
    //        return "ERROR";
    //    }
    //}

}
